import React from "react";
import _ from 'lodash';
import { Form, Select, Input, InputNumber, Button, Space, Cascader, Tag, Switch } from "antd";
import Sku from "./Sku";
import TheUpload from "@/components/TheUpload";
import TheButton from "@/components/TheButton";
import TheQuill from "@/components/TheQuill";
import TheTable from "@/components/TheTable";
import TheDialog from "@/components/TheDialog";
import GoBack from "@/components/TheGoBack";
import { apiGetGoodsClassifyTree, apiGetGoodsSpecificationsList, apiGetBrandInfoList, apiGetGoodsInfoInsert, apiGetFreightTemplateList, apiGetBrandInfoAdd, apiGetGoodsInfoUpdateState } from '@/request/mallManagement'
import "../../style/style.less";
import Brand from "./Brand";
const { TextArea } = Input;

class Add extends React.Component {
  state = {
    currentIndex: 1,
    skuPropertyArray: [],
    skuPropertyTable: [],
    skuType: "",
    numResult: [],
    options: [],
    productTxt: '',
    parameterColumns: [
      {
        title: '参数项',
        dataIndex: 'specificationsName',
        key: 'specificationsName'
      },
      {
        title: '值',
        dataIndex: 'specificationsValue',
        key: 'specificationsValue',
        render: (text, record, index) => {
          return <Input
            onChange={e => {
              let value = {
                ...record,
                specificationsValue: e.target.value
              }
              let data = _.cloneDeep(this.state.parameterDataSource)
              data.splice(index, 1, value)
              this.setState({
                parameterDataSource: data
              })
            }}
          />
        }
      },
      {
        title: '操作',
        render: (text, record, index) => {
          return <TheButton onClick={() => this.delConfirm(record, index)}>删除</TheButton>
        }
      }
    ],
    parameterDataSource: [],
    visible: false,
    brandOptions: [],
    goodsTagOptions: [],
    freightTemplateId: '',
    templateOptions: [],
    specificationsDetailedInfo: [],
    alias: ''
  };
  delConfirm = (record, index) => {
    const { parameterDataSource } = this.state
    if (parameterDataSource.length > 1) {
      React.$confirm({
        title: '您确认删除此项参数信息吗？',
        onOk: () => {
          let data = _.cloneDeep(parameterDataSource)
          data = data.splice(index + 1, 1)
          this.setState({
            parameterDataSource: data
          })
        }
      })
    } else {
      React.$message({
        type: 'info',
        content: '仅剩余一项无法删除'
      })
    }
  }
  async componentDidMount() {
    await this.getClassifyList()
    await this.getTemplate()
    await this.getGoodsTag()
    await this.getBrandInfoList()
  }
  getTemplate = async () => {
    let res = await apiGetFreightTemplateList()
    if (res.data && res.code === 0) {
      let options = res.data.map(v => {
        return {
          label: v.freightTemplateName,
          value: v.freightTemplateId
        }
      })
      this.setState({
        templateOptions: options
      })
    }
  }
  getClassifyList = async () => {
    let res = await apiGetGoodsClassifyTree()
    this.setState({
      options: res.data
    })
  }
  getGoodsTag = async () => {
    let res = await React.$post('/management/tSysDictionaries/list', { type: "goods_tag" })
    let goodsTagOptions = []
    res.data.map((v) => {
      goodsTagOptions.push({ label: v.name, value: v.dictionariesId })
    })
    this.setState({
      goodsTagOptions
    })
  }
  getFileResult = (value) => {
    if (value.length) {
      let str = value.map(v => {
        if (v.response && v.response.code === 0) {
          return v.response.data
        }
      }).join(',')
      this.formRef.setFieldsValue({ goodsShowImages: str });
    } else {
      this.formRef.setFieldsValue({ goodsShowImages: '' });
    }
  };
  /**
   * @desc 设置新闻内容表单默认值
   * */
  setNewsContent = (data) => {
    const len = data.replace(/(<p>|<\/p>)/g, '').trim().length
    if (!len) {
      this.setState({
        productTxt: " "
      })
    } else {
      this.setState({
        productTxt: data
      })
    }
  };
  setCurrentIndex = async (index) => {
    console.log(this.formRef.getFieldsValue());
    let status = true
    await this.formRef.validateFields().catch(err => {
      status = false
    })
    if (!status) {
      status = false
      return React.$message({
        type: 'info',
        content: '请填写完整的商品基本信息'
      })
    }
    let productInfoJson = this.formRef.getFieldsValue()
    productInfoJson.originalPrice = React.$transNum(productInfoJson.originalPrice, 0, 2)
    productInfoJson.currentPrice = React.$transNum(productInfoJson.currentPrice, 0, 2)
    console.log(productInfoJson.goodsClassifyId)
    productInfoJson.goodsClassifyId = productInfoJson.goodsClassifyId.join(',')
    productInfoJson.goodsTag = productInfoJson.goodsTag ? productInfoJson.goodsTag.join(',') : ""
    this.setState({
      productInfoJson
    })
    let { skuPropertyArray, skuPropertyTable, numResult, freightTemplateId, parameterDataSource } = this.state
    numResult = numResult && numResult.length && numResult.map(v => {
      return {
        ...v,
        isChecked: false,
      }
    })

    if (!freightTemplateId) {
      status = false
      return React.$message({
        type: 'info',
        content: '请选择运费模板'
      })
    }
    const specificationsDetailedInfo = parameterDataSource.map(v => {
      return {
        specificationsName: v.specificationsName,
        specificationsValue: v.specificationsValue
      }
    })
    if (!_.every(specificationsDetailedInfo)) {
      status = false
      return React.$message({
        type: 'info',
        content: '请填写完整的商品参数信息'
      })
    }
    const productSkuJson = JSON.stringify({ skuPropertyTable, numResult, skuPropertyArray })
    const findEmpty = value => {
      value.forEach(v => {
        delete v.isChecked
        if (!v.skuOriginalPrice) {
          status = false
        }
        if (!v.skuCurrentPrice) {
          status = false
        }
        // if (!v.materialId) {
        //   status = false
        // }
        if (!v.materialName) {
          status = false
        }
        if (!v.skuWeight) {
          status = false
        }
        if (!v.imageFile) {
          status = false
        }
      })
      return status
    }
    skuPropertyArray.forEach(v => {
      if (!v.name) {
        return status = false
      }
    })
    if (!status) {
      return React.$message({
        type: 'info',
        content: '规格标题不能为空'
      })
    }
    if (!numResult) {
      return React.$message({
        type: 'info',
        content: '请填写完整的SKU信息'
      })
    }
    if (!findEmpty(numResult)) {
      return React.$message({
        type: 'info',
        content: '请填写完整的SKU信息'
      })
    }
    numResult = numResult.map(v => {
      return {
        ...v,
        skuOriginalPrice: React.$transNum(v.skuOriginalPrice, 0, 2),
        skuCurrentPrice: React.$transNum(v.skuCurrentPrice, 0, 2),
        skuWeight: React.$transNum(v.skuWeight, 0, 3),
      }
    })
    // let materialId = numResult.map(v => _.toString(v.materialId))
    // let uniqmaterialId = _.uniq(materialId)
    // if (_.size(materialId) !== _.size(uniqmaterialId)) {
    //   return React.$message({
    //     type: 'info',
    //     content: '物料ID不能相同'
    //   })
    // }
    let material = /^[A-Za-z0-9]+$/;
    let flag = false
    let con = false
    let arr1 = numResult.reduce((pre, cur, index) => {
      // console.log(pre, cur);
      if (pre.includes(cur.materialId) && cur.materialId) {
        flag = true
        return pre
      }
      if (cur.materialId) {
        if (!material.test(cur.materialId)) {
          con = true
        }
      }
      pre.push(cur.materialId)
      return pre
    }, [])
    if (con) {
      return React.$message({
        type: 'info',
        content: '物料ID只能为字母和数字'
      })
    }
    if (flag) {
      return React.$message({
        type: 'info',
        content: '物料ID不能相同'
      })
    }
    let productStock = numResult.map(v => {
      return v.stock
    })
    productStock = _.sum(productStock)
    let arr = []
    if (numResult.length === 1) {
      if (skuPropertyTable[0].length > 1) {
        arr = _.zip(skuPropertyTable, numResult)
      } else {
        if (Array.prototype.isPrototypeOf(skuPropertyTable[0])) {
          arr = _.zip(skuPropertyTable[0], numResult)
        } else {
          let table = _.flatten(skuPropertyTable)
          arr = _.zip(table, numResult)
        }
      }
    } else {
      if (skuPropertyTable.length !== numResult.length) {
        arr = _.zip(_.flatten(skuPropertyTable), numResult)
      } else {
        arr = _.zip(skuPropertyTable, numResult)
      }
    }
    const skuInfo = arr.map((v, i) => {
      let skuAttribute = null
      let b = null
      if (Array.prototype.isPrototypeOf(v[0])) {
        skuAttribute = v[0].map((v, i) => {
          return {
            key: v.name,
            value: v.itemName
          }
        })
      } else if (Object.prototype.isPrototypeOf(v[0])) {
        skuAttribute = [
          {
            key: v[0].name,
            value: v[0].itemName
          }
        ]
      }
      if (Object.prototype.isPrototypeOf(v[1])) {
        b = v[1]
      }
      // delete b.isChecked
      return {
        ...b,
        skuAttribute,
      }
    })
    this.setState({
      skuInfoJson: JSON.stringify(skuInfo),
      specificationsDetailedInfo,
      productSkuJson,
      productStock
    })
    console.log(this.state)
    if (status)
      this.setState({ currentIndex: index });
  };
  /**
   * @desc 获取sku返回值
   * */
  getSkuProperty = (skuPropertyArray, skuPropertyTable, skuType) => {
    let arr = [];
    if (skuPropertyTable.length > 0) {
      if (
        Object.prototype.toString.call(skuPropertyTable[0]) ===
        "[object Object]"
      ) {
        skuPropertyTable.forEach((v) => {
          arr.push(v);
        });
        arr = [arr];
      } else {
        arr = skuPropertyTable;
      }
    }
    this.setState({ skuPropertyArray, skuPropertyTable: arr, skuType });
  };
  /**
   * @desc 获取sku价格返回值
   * */
  getNumResult = (numResult) => {
    this.setState({ numResult });
  };
  goback = () => {
    this.props.history.go(-1);
  };
  onSubmit = async () => {
    this.setState({ btnLoading: true })
    if (this.state.currentIndex === 2) {
      if (!this.state.productTxt.trim()) {
        this.setState({ btnLoading: false })
        return React.$message({
          type: 'info',
          content: '商品规格信息为必填信息'
        })
      } else {
        let { productInfoJson, productSkuJson, productTxt, skuInfoJson, productStock, specificationsDetailedInfo, freightTemplateId } = this.state
        let goodsInfoJson = JSON.stringify({ ...productInfoJson, otherDelivery: productInfoJson.otherDelivery ? 1 : 0, productSkuJson, productTxt, productStock, freightTemplateId })
        let specificationsDetailedInfoJson = ''
        if (specificationsDetailedInfo.length != 0) {
          specificationsDetailedInfoJson = JSON.stringify(specificationsDetailedInfo)
        }
        let res = await apiGetGoodsInfoInsert({ goodsInfoJson, skuInfoJson, specificationsDetailedInfoJson })
        if (res.code === 0) {
          let response = await apiGetGoodsInfoUpdateState({ goodsId: res.data, reviewStatus: 'S' })
          if (response.code === 0) {
            React.$message({
              type: 'info',
              content: '新商品发布成功'
            })
            this.props.history.goBack()
          }
        }
      }
    }
    this.setState({ btnLoading: false })
  }
  onSave = async () => {
    this.setState({ btnLoading: true })
    if (this.state.currentIndex === 2) {
      if (!this.state.productTxt.trim()) {
        this.setState({ btnLoading: false })
        return React.$message({
          type: 'info',
          content: '商品规格信息为必填信息'
        })
      } else {
        let { productInfoJson, productSkuJson, productTxt, skuInfoJson, productStock, specificationsDetailedInfo, freightTemplateId } = this.state
        let goodsInfoJson = JSON.stringify({ ...productInfoJson, otherDelivery: productInfoJson.otherDelivery ? 1 : 0, productSkuJson, productTxt, productStock, freightTemplateId })
        let specificationsDetailedInfoJson = ''
        if (specificationsDetailedInfo.length != 0) {
          specificationsDetailedInfoJson = JSON.stringify(specificationsDetailedInfo)
        }
        console.log(goodsInfoJson, skuInfoJson,'goodsInfoJson, skuInfoJson');
        let res = await apiGetGoodsInfoInsert({ goodsInfoJson, skuInfoJson, specificationsDetailedInfoJson })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '新商品保存成功'
          })
          this.props.history.goBack()
        }
      }
    }
    this.setState({ btnLoading: false })
  }
  openApplyDialog = () => {
    this.setState({
      visible: true
    })
  }
  closeApplyDialog = () => {
    this.setState({
      visible: false
    })
  }
  getApplyFileResult = file => {
    if (file.length && file[0].response && file[0].response.code === 0) {
      const id = file[0].response.data;
      this.applyRef.setFieldsValue({ brandImg: id });
    } else {
      this.applyRef.setFieldsValue({ brandImg: "" });
    }
  }
  getBrandInfoList = async () => {
    let response = await apiGetBrandInfoList()
    if (response.data && response.code === 0) {
      let brandOptions = response.data.map(v => {
        return {
          value: v.brandId,
          label: v.brandName
        }
      })
      this.formRef.setFieldsValue({ brandId: null })
      this.setState({
        brandOptions,
        brandId: null
      })
    }
  }
  cascaderChange = async value => {


  }
  saveApplyDialog = async value => {
    let res = await apiGetBrandInfoAdd({ ...value })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '申请成功，请等待审核'
      })
      this.setState({
        visible: false
      })
    } else {
      this.setState({ visible: false })
    }
  }
  brandIdChange = (e) => {
    this.formRef.setFieldsValue({ brandId: e })
    this.setState({ brandId: e })
  }
  goodsTagChange = (props) => {
    const { label, value, closable, onClose } = props;
    const onPreventMouseDown = (event) => {
      event.preventDefault();
      event.stopPropagation();
    };
    this.formRef.setFieldsValue({ goodsTag: props })
    return (
      <Tag
        onMouseDown={onPreventMouseDown}
        closable={closable}
        onClose={onClose}
        style={{
          marginRight: 3,
        }}
      >
        {label}
      </Tag>
    );
  }
  render() {
    const { currentIndex, btnLoading, parameterColumns, parameterDataSource, visible, brandOptions, templateOptions, disabled, brandId, goodsTag, goodsTagOptions, alias } = this.state;
    return (
      <div className="p-layout-box commodity-list-add">
        <GoBack history={this.props.history} title={"新增商品"} />
        <div className="content">
          <div style={{ display: currentIndex === 1 ? "block" : "none" }}>
            <div>
              <div className="title">基本信息</div>
              <div className="form-box">
                <Form ref={ref => this.formRef = ref}>
                  <Form.Item label="商品分类" name={'goodsClassifyId'} rules={[{ required: true }]}>
                    <Cascader onChange={(value, selectedOptions) => this.cascaderChange(value, selectedOptions)} placeholder="请选择商品分类" options={this.state.options} />
                  </Form.Item>
                  <Form.Item label="商品标签" name={'goodsTag'} rules={[{ required: false }]}>
                    <div style={{ display: 'flex', columnGap: 10 }}>
                      <Select value={goodsTag} mode={"tags"} onChange={(value) => this.goodsTagChange(value)} placeholder="请选择标签" options={goodsTagOptions} />
                    </div>
                  </Form.Item>
                  <Form.Item label="品牌名称" name={'brandId'} >
                    <div style={{ display: 'flex', columnGap: 10 }}>
                      <Select showSearch value={brandId} onChange={this.brandIdChange} placeholder="请选择品牌" options={brandOptions} filterOption={(input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                      } />
                      <Button type="primary" onClick={this.openApplyDialog}>申请品牌</Button>
                    </div>
                  </Form.Item>

                  <Form.Item label="商品名称" name={'goodsName'} rules={[{ required: true }, { max: 100 }, { whitespace: true }]}>
                    <Input placeholder="请输入商品名称" />
                  </Form.Item>

                  <Form.Item label="商品原价" name={'originalPrice'} rules={[{ required: true }, {
                    pattern: /^\d+(\.\d{0,2})?$/,
                    message: '只能输入正数且最多两位小数'
                  }]}>
                    <InputNumber max={10000000} min={0.01} placeholder="请输入商品原价" />
                  </Form.Item>

                  <Form.Item label="商品现价" name={'currentPrice'} rules={[{ required: true }, {
                    pattern: /^\d+(\.\d{0,2})?$/,
                    message: '只能输入正数且最多两位小数'
                  }]}>
                    <InputNumber max={10000000} min={0.01} placeholder="请输入商品现价" />
                  </Form.Item>

                  <Form.Item label="商品图片" name={'goodsShowImages'} rules={[{ required: true }]}>
                    <TheUpload getFileResult={this.getFileResult} len={5} />
                  </Form.Item>
                  <Form.Item label="代发货商品" name={'otherDelivery'} >
                    <Switch></Switch>
                  </Form.Item>
                </Form>
              </div>
            </div>
            <div>
              <div className="title">商品交易信息</div>
              <div className="mall-trading">
                <div>
                  <span>运费模板</span>
                  <Select
                    options={templateOptions}
                    onChange={e => this.setState({ freightTemplateId: e })}
                    style={{ width: 300 }}
                    placeholder="请选择运费模板" />
                </div>
              </div>
            </div>
            {/* <div>
              <div className="title">商品参数信息</div>
              <div style={{ padding: '0 20px 20px' }}>
                <TheTable columns={parameterColumns} dataSource={parameterDataSource} />
              </div>
            </div> */}
            <div>
              <div className="title">商品规格信息</div>
              <Sku
                getSkuProperty={this.getSkuProperty}
                getNumResult={this.getNumResult}
                alias={alias}
              />
            </div>
          </div>
          <div style={{ display: currentIndex === 2 ? "block" : "none" }}>
            <div className="title">商品规格信息</div>
            <div style={{ width: '90%', margin: 'auto' }}>
              <TheQuill style={{ height: 500 }} defaultValue={" "} setNewsContent={this.setNewsContent} />
            </div>
          </div>
        </div>
        <div className="button-group">
          <Button type="default" size="middle" onClick={this.goback}>
            取消
          </Button>

          {currentIndex === 1 && (
            <Button
              style={{ backgroundColor: "#F59A23", color: "#fff" }}
              size="middle"
              disabled={disabled}
              onClick={() => this.setCurrentIndex(2)}
            >
              下一页
            </Button>
          )}

          {currentIndex === 2 && (
            <div>
              <Button
                type="default"
                size="middle"
                onClick={() => this.setCurrentIndex(1)}
              >
                上一步
              </Button>
              <Button
                style={{ backgroundColor: "#F59A23", color: "#fff" }}
                size="middle"
                onClick={this.onSubmit}
                loading={btnLoading}
              >
                发布
              </Button>
              <Button
                style={{ backgroundColor: "#F59A23", color: "#fff" }}
                size="middle"
                onClick={this.onSave}
                loading={btnLoading}
              >
                保存
              </Button>
            </div>
          )}
        </div>
        <TheDialog
          title="申请品牌"
          visible={visible}
          footer={null}
          width={400}
          handleCancel={this.closeApplyDialog}
        >
          <Brand onFinish={this.saveApplyDialog} handleCancel={this.closeApplyDialog} />
        </TheDialog>
      </div>
    );
  }
}

export default Add;
